<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>视频平台</title>
    <link rel="icon" type="image/x-icon" href="/live/favicon.ico" />
    <link rel="stylesheet" href="/live/css/style.css" />
    <link rel="stylesheet" href="/live/css/flatpickr.min.css" />
    <style>
      html,
      body {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
        background-color: rgb(36, 49, 84);
        color: #dadada;
        overflow: hidden;
      }

      .header {
        width: 100%;
        height: 50px;
        line-height: 50px;
        padding: 0 30px;
        font-size: 18px;
        font-weight: 900;
      }

      .content {
        width: 100%;
        height: calc(100% - 50px);
      }

      .videoView {
        width: calc(100% - 400px);
        height: 100%;
        float: left;
        overflow: hidden;
        border-top: 2px solid #1b2b50;
      }

      #videoTool {
        max-height: 120px;
        overflow: hidden;
        line-height: 50px;
        margin: 0 30px;
        box-sizing: border-box;
      }

      #video {
        width: calc(100% - 80px);
        height: calc(100% - 200px);
        background-color: rgba(0, 0, 0, 0.5);
        margin: 0 30px;
        border-radius: 5px;
        /* box-shadow: 16px 14px 20px 0px #01094a;
        box-shadow: 20px 20px 20px 0px #000000;*/
        overflow: hidden;
      }

      canvas {
        width: 100%;
        height: 100%;
        float: left;
        background-color: rgb(112, 112, 112);
      }

      .IPCList {
        width: 400px;
        height: 100%;
        float: left;
        background-color: #1a2544;
        overflow: hidden;
      }

      #videoTool {
        position: relative;
        padding-top: 15px;
      }

      #ipcListUl {
        width: 100%;
        height: 100%;
        overflow: auto;
      }

      #videoTool ul li {
        display: inline-block;
        padding: 2px 12px 2px 30px;
        border: 1px solid #9098b2;
        border-radius: 5px;
        height: 25px;
        line-height: 18px;
        margin-right: 10px;

        background-repeat: no-repeat;
        background-position: 10px center;
        background-size: 12px;
        font-size: 12px;
        cursor: pointer;
      }

      #videoTool .leftUl li {
        background-image: url('/live/icons/bottom.png');
      }

      #videoTool .leftUl .playbackbtn {
        background-color: #0c8617;
      }

      /* #videoTool ul.rightUl li.on {
        background-color: #7990de;
      }

      #videoTool ul.rightUl li {
        padding-right: 40px;
      }

      #videoTool ul.rightUl li a {
        border-left: 1px solid #a2b7ef;
        padding-left: 10px;
      } */

      #videoTool ul li a {
        color: #c6d5ef;
      }

      #videoTool .rightUl {
        position: absolute;
        right: 10px;
        top: 15px;
      }

      #videoTool .rightUl #download {
        background-image: url('/live/icons/download.png');
      }

      .IPCList #ipcListUl li {
        width: 100%;
        overflow: hidden;
        padding: 10px 35px;
        border-bottom: 1px solid #29324f;
      }

      .IPCList #ipcListUl li > div {
        float: left;
        font-size: 12px;
      }

      .IPCList #ipcListUl li > div img {
        width: 50px;
        margin-right: 40px;
        cursor: pointer;
      }

      .timeIput {
        background: rgba(0, 0, 0, 0.02);
        border: none;
        color: #fff;
        padding: 3px;
      }

      .playIng {
        width: 40px;
        height: 40px;
        float: right !important;
        background-image: url('/live/icons/video.png');
        background-repeat: no-repeat;
        background-position: 10px center;
        background-size: 25px;
        display: none;
      }

      .show .playIng {
        display: inline;
      }

      #channel {
        width: 50px;
        color: white;
        border: none;
        outline: none;
        background-color: rgba(0, 0, 0, 0);
      }
      #channel option {
        background-color: #243154;
      }

      #cameraIP {
        width: 50px;
        color: white;
        border: none;
        outline: none;
        background-color: rgba(0, 0, 0, 0);
      }
      #cameraIP option {
        background-color: #243154;
      }
      .IPCList .ipcListTitle {
        width: 100%;
        height: 40px;
        line-height: 40px;
        text-align: center;
        /* background-color: #243154; */
        border-bottom: #393a3b 1px solid;
      }
    </style>
  </head>

  <body>
    <div class="header uniqueElement">VideoServer | 视频平台</div>
    <div class="content">
      <div class="videoView">
        <div id="videoTool">
          <ul class="leftUl">
            <li>
              开始时间：<input id="startTimeInp" class="timeIput" type="text" />
            </li>
            <li>
              结束时间：<input id="endTimeInp" class="timeIput" type="text" />
            </li>
            <li>
              通道号：
              <select name="" id="channel">
                <option></option>
                <option value="1">33</option>
              </select>
            </li>
            <li>
              摄像机：
              <select name="" id="cameraIP">
                <option></option>
                <option value="127.0.0.1">127.0.0.1</option>
              </select>
            </li>
            <li class="on playbackbtn" onclick="hisPlay()">播放回放</li>
          </ul>
          <ul class="rightUl">
            <li id="download" onclick="download()">下载回放</li>
          </ul>
        </div>
        <div id="video">
          <canvas id="video-canvas"> </canvas>
        </div>
      </div>
      <ul class="pie">
        <!-- <li class="slice-one slice hvr-fade" code="21">
          <img src="/icons/top.png" alt="" />
        </li>
        <li class="slice-two slice hvr-fade" code="26">
          <img src="/icons/top.png" alt="" />
        </li>
        <li class="slice-three slice hvr-fade" code="24">
          <img src="/icons/top.png" alt="" />
        </li>
        <li class="slice-four slice hvr-fade" code="28">
          <img src="/icons/top.png" alt="" />
        </li>
        <li class="slice-five slice hvr-fade" code="22">
          <img src="/icons/top.png" alt="" />
        </li>
        <li class="slice-six slice hvr-fade" code="27">
          <img src="/icons/top.png" alt="" />
        </li>
        <li class="slice-seven slice hvr-fade" code="23">
          <img src="/icons/top.png" alt="" />
        </li>
        <li class="slice-eight slice hvr-fade" code="25">
          <img src="/icons/top.png" alt="" />
        </li> -->
        <div class="pieCenter play"></div>
      </ul>
      <div class="IPCList">
        <div class="ipcListTitle">
          <h1>实时播放摄像机列表</h1>
        </div>
        <ul id="ipcListUl"></ul>
      </div>
    </div>
    <script src="/live/js/jquery.js"></script>
    <script src="/live/js/jsmpeg.min.js"></script>
    <script src="/live/js/moment.js"></script>
    <script src="/live/js/flatpickr.js"></script>
    <script src="/live/js/uuid.min.js"></script>
    <script>
      // 生成一个 clientID
      const clientID =
        JSON.parse(sessionStorage.getItem('video-uuid')) || uuid.v4();
      // console.log(clientID);

      // ====== 接口服务器请求地址 start ======
      const IP = window.location.hostname;
      const PORT = window.location.port;
      const serverIp = IP + ':' + PORT;

      // ====== 存储播放信息 ======
      const setPlayInfo = (playInfo) => {
        sessionStorage.setItem('playInfo', JSON.stringify(playInfo));
      };
      const getPlayInfo = () => {
        return JSON.parse(sessionStorage.getItem('playInfo'));
      };

      // ====== 全局变量 ======
      var player = null; // 播放实例
      var playHistoryInfo = getPlayInfo(); // 播放历史视频的信息
      var startTimestamp, endTimestamp, channel, cameraIP;
      var downloadFlag = true;

      // ====== 函数 ======
      function destroyPlayer(play) {
        if (play) {
          player.destroy();
        }
      }
      // 暂停
      function pauseVideo() {
        if (player) {
          player.pause();
        }
        // sendCommandToServer('pause')
      }
      // 播放
      function playVideo() {
        if (player) {
          player.play();
        }
        // sendCommandToServer('play');
      }
      // 播放与暂停样式
      function playerStyleController(className) {
        if (className === 'play') {
          $('.pieCenter').removeClass('play');
          $('.pieCenter').addClass('pause');
        } else {
          $('.pieCenter').removeClass('pause');
          $('.pieCenter').addClass('play');
        }
      }

      // ====== 刷新页面-清空播放 ======
      sessionStorage.setItem('video-uuid', JSON.stringify(clientID));
      $.ajax({
        url: `http://${serverIp}/live`,
        type: 'post',
        data: { clientID },
        success: function (res) {},
        error: function (err) {},
      });

      // ====== 获取视频列表接口 ======
      function getIPCList(data = {}) {
        $.ajax({
          url: `http://${serverIp}/live/ipcList`,
          type: 'post',
          data,
          success: function (res) {
            // console.log(res);
            let html = '';
            res.forEach((item) => {
              html += `
                <li onclick="play('${item.id}')" channel=${item.channel}>
                      <div>
                          <img src="/live/icons/play.png">
                      </div>
                      <div>
                          <p>名称：${item.name}</p>
                          <p>类型：${item.type}</p>
                          <p>摄像头：${item.cameraIp}</p>
                      </div>
                      <div class="playIng"></div>
                </li>
              `;
            });

            $('#ipcListUl').html(html);
            $('#ipcListUl li').click(function () {
              var li = $('#ipcListUl li');
              for (var i = 0; i < li.length; i++) {
                $(li[i]).removeClass('show');
              }
              $(this).addClass('show');
            });
          },
          error: function (err) {
            var html = `
                <li>
                      <div>
                          <img src="/live/icons/play.png">
                      </div>
                      <div>
                        <p>⠀</p>
                        <p>暂无播放源</p>
                        <p>⠀</p>
                      </div>
                      <div class="playIng"></div>
                </li>
              `;

            $('#ipcListUl').html(html);
            $('#ipcListUl li').click(function () {
              var li = $('#ipcListUl li');
              for (var i = 0; i < li.length; i++) {
                $(li[i]).removeClass('show');
              }
              $(this).addClass('show');
            });
          },
        });
      }
      getIPCList();

      // ====== 播放实时视频 ======
      function transCodeApi(data) {
        $.ajax({
          url: `http://${serverIp}/live/play`,
          type: 'post',
          data,
          success: (res) => {
            destroyPlayer(player);
            $('#video').html('<canvas id="video-canvas"></canvas>');
            const url = `ws://${serverIp}/videoService/clientID=${clientID}&cameraID=${res.cameraID}`;
            const canvas = document.getElementById('video-canvas');
            player = new JSMpeg.Player(url, {
              canvas: canvas,
              videoBufferSize: 1024 * 1024 * 4,
            });
          },
          error: function (err) {},
        });
      }
      async function play(id) {
        await transCodeApi({ clientID, cameraID: id });
        playerStyleController('play');
      }

      // ====== 播放历史视频 ======
      function playHistoryApi(data) {
        $.ajax({
          url: `http://${serverIp}/live/getHis`,
          type: 'post',
          data,
          timeout: 30000,
          success: function (res) {
            destroyPlayer(player);
            frameData = []; // 用于存储每一帧的数据
            const camera = startTimestamp + endTimestamp;
            $('#video').html('<canvas id="video-canvas"> </canvas>');
            const url = `ws://${serverIp}/videoService/clientID=${clientID}&cameraID=${camera}`;
            const canvas = document.getElementById('video-canvas');
            player = new JSMpeg.Player(url, {
              canvas: canvas,
              videoBufferSize: 1024 * 1024 * 4,
            });
          },
          error: function (res) {
            if (res.textStatus === 'timeout') {
              // 处理超时的情况
              alert('请求超时，请检查网络连接或稍后再试');
            } else {
              // 其他错误情况
              alert('播放资源出错！');
            }
          },
        });
      }
      async function hisPlay() {
        $('.playIng').removeClass('show');
        channel = $('#channel').val();
        cameraIP = $('#cameraIP').val();
        if (!startTimestamp || !endTimestamp || !channel || !cameraIP) {
          alert('请选择时间和通道');
          return;
        }
        if (startTimestamp >= endTimestamp) {
          alert('开始时间不能大于或等于结束时间！');
          return;
        }

        $('#ipcListUl li').removeClass('show');
        await playHistoryApi({
          ip: IP,
          startTimestamp,
          endTimestamp,
          channel,
          cameraIP,
          clientID,
          cameraID: startTimestamp + endTimestamp,
        });
        setPlayInfo({ startTimestamp, endTimestamp, channel, cameraIP });
        playerStyleController('play');
      }

      // ====== 下载回放 ======
      function downloadApi(data) {
        if (downloadFlag) {
          // 下载的逻辑
          downloadFlag = false;
          $('#download').text('下载中...');
          const url = `http://${serverIp}/live/download`;
          fetch(url, {
            method: 'POST', // 或者 'PUT'
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
          })
            .then((response) => {
              if (response.status === 200) {
                return response.blob();
              } else {
                alert('下载失败：' + response.statusText);
                return Promise.reject('下载失败：' + response.statusText);
              }
            })
            .then((data) => {
              downloadFlag = true;
              $('#download').text('下载回放');
              if (data.type === 'video/mp4') {
                const url = URL.createObjectURL(data);
                var a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                a.download = 'video.mp4';
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
              } else {
                console.log(data);

                window.alert('已取消下载');
              }
            })
            .catch((error) => {
              downloadFlag = true;
              $('#download').text('下载回放');
              console.error('Error:', error);
            });
        } else {
          // 终止的逻辑
          downloadFlag = true;
          $('#download').text('下载回放');
          $.ajax({
            url: `http://${serverIp}/live/downloadEnd`,
            type: 'post',
            data: { clientID },
            success: function (res) {},
            error: function (res) {},
          });
        }
      }
      function download() {
        channel = $('#channel').val();
        cameraIP = $('#cameraIP').val();

        if (!startTimestamp || !endTimestamp || !channel || !cameraIP) {
          alert('请选择时间和通道');
          return;
        }
        if (startTimestamp >= endTimestamp) {
          alert('开始时间不能大于或等于结束时间！');
          return;
        }
        setPlayInfo({ startTimestamp, endTimestamp, channel, cameraIP });
        downloadApi({
          ip: IP,
          startTimestamp,
          endTimestamp,
          channel,
          cameraIP,
          clientID,
        });
      }

      $(document).ready(function () {
        // ====== 持久化处理 ======
        if (playHistoryInfo) {
          startTimestamp = playHistoryInfo.startTimestamp;
          endTimestamp = playHistoryInfo.endTimestamp;
          channel = playHistoryInfo.channel;
          cameraIP = playHistoryInfo.cameraIP;
          $('#startTimeInp').val(
            moment(new Date(startTimestamp)).format('YYYY-MM-DD HH:mm:ss')
          );
          $('#endTimeInp').val(
            moment(new Date(endTimestamp)).format('YYYY-MM-DD HH:mm:ss')
          );
          $('#channel').val(channel);
          $('#cameraIP').val(cameraIP);
        }
        // ====== 播放按钮样式处理 ======
        $('.pieCenter').click(function () {
          let playState = $(this).attr('class').split(' ')[1];

          if (playState === 'play') {
            // 播放的逻辑
            if (!player) {
              alert('请选择播放源');
              return;
            }
            playVideo();
          } else {
            // 暂停的逻辑
            pauseVideo();
          }
          playerStyleController(playState);
        });
      });

      // ====== 日期选择器处理 ======
      const chineseMonths = [
        '一月',
        '二月',
        '三月',
        '四月',
        '五月',
        '六月',
        '七月',
        '八月',
        '九月',
        '十月',
        '十一月',
        '十二月',
      ];

      flatpickr.l10ns.zh = {
        weekdays: {
          shorthand: ['日', '一', '二', '三', '四', '五', '六'],
          longhand: [
            '星期日',
            '星期一',
            '星期二',
            '星期三',
            '星期四',
            '星期五',
            '星期六',
          ],
        },
        months: {
          shorthand: chineseMonths,
          longhand: chineseMonths,
        },
        firstDayOfWeek: 1, // 星期一为一周的第一天
      };

      // 应用中文语言包
      flatpickr.defaultConfig.locale = flatpickr.l10ns.zh;

      // 获取当前时间
      var now = new Date();
      // 初始化日期时间选择器-开始时间
      flatpickr('#startTimeInp', {
        enableTime: true, // 启用时间选择
        dateFormat: 'Y-m-d H:i:ss', // 设置日期时间格式
        time_24hr: true, // 使用24小时制显示时间
        maxDate: now,
        onValueUpdate: function (selectedDates, dateStr, instance) {
          startTimestamp = new Date(dateStr).getTime();
          // console.log('startTimestamp--->:', startTimestamp);
        },
      });

      // 初始化日期时间选择器-结束时间
      flatpickr('#endTimeInp', {
        enableTime: true, // 启用时间选择
        dateFormat: 'Y-m-d H:i:ss', // 设置日期时间格式
        time_24hr: true, // 使用24小时制显示时间
        maxDate: now,
        onValueUpdate: function (selectedDates, dateStr, instance) {
          endTimestamp = new Date(dateStr).getTime();
          // console.log('endTimestamp--->:', endTimestamp);
        },
      });

      // ====== 清理资源 ======
      window.onbeforeunload = function (event) {
        $.ajax({
          url: `http://${serverIp}/live/close`,
          type: 'post',
          data: { clientID },
          success: function (res) {},
          error: function (res) {},
        });
        return null;
      };
    </script>
  </body>
</html>
